package net.spider.bttiantang;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.helper.StringUtil;
import org.viva.api.HTTPUtils;
import org.viva.entity.cms.Movie;

import net.spider.tools.page.MatchType;
import net.spider.tools.page.PageHelper;
import net.spider.tools.page.PickUpItem;

public class Page {

    String baseUrl = "http://www.bttiantang.com";

    public int getPageCount(String url) throws IOException {
        // String indexPage = FileUtils.readFileToString(new
        // File("D://test/btTianTangIndexPage.txt"));
        String indexPage = HTTPUtils.doGet(url);
        // 构建提取内容
        PickUpItem item = new PickUpItem();
        item.setMatchType(MatchType.Css);
        item.setName("name");
        item.setPattern("div > .ml > .pagelist > li > .pageinfo > strong");

        // 提取内容
        PageHelper page = new PageHelper();
        page.setDocument(Jsoup.parse(indexPage));
        page.addPatternParts(item);
        List<PickUpItem> items = page.run().get("name");
        Object pageCount = items.get(0).getTargetElement().html();
        return Integer.valueOf(pageCount.toString());
    }

    public List<Movie> getMovieFormPage(String url) throws IOException {
        List<Movie> targetList = new ArrayList<>();
        String pageOfHtml = HTTPUtils.doGet(url);
        // String pageOfHtml = FileUtils.readFileToString(new
        // File("D://test/btTianTangIndexPage.txt"));
        // 构建提取内容
        PickUpItem item = new PickUpItem();
        item.setMatchType(MatchType.Css);
        item.setName("pageListItemFromIndex");
        item.setPattern("div > .ml > .item");
        // 提取内容
        PageHelper pagehelper = new PageHelper();
        pagehelper.setDocument(Jsoup.parse(pageOfHtml));
        pagehelper.addPatternParts(item);
        Map<String, List<PickUpItem>> items = pagehelper.run();
        for (PickUpItem item1 : items.get("pageListItemFromIndex")) {
            Movie movie = getMovieFromPageListPart(item1.getTargetElement().html());
            if (null != movie) {
                targetList.add(movie);
            }
        }

        return targetList;
    }

    private Movie getMovieFromPageListPart(String content) {
        // TODO 有广告需要过滤出去，有<script>标签的可以直接跳过不处理
        // code
        PickUpItem nameAndTimeItem = new PickUpItem();
        nameAndTimeItem.setMatchType(MatchType.Css);
        nameAndTimeItem.setName("cnNameEnNameOrReleaseTime");
        nameAndTimeItem.setPattern(".title > .tt > a > b");

        PickUpItem actorsItem = new PickUpItem();
        actorsItem.setMatchType(MatchType.Css);
        actorsItem.setName("actors");
        actorsItem.setPattern(".title > .des");

        PickUpItem urlItem = new PickUpItem();
        urlItem.setMatchType(MatchType.Css);
        urlItem.setName("url");
        urlItem.setPattern(".title > .tt > a");

        PickUpItem doubanScore = new PickUpItem();
        doubanScore.setMatchType(MatchType.Css);
        doubanScore.setName("doubanScore");
        doubanScore.setPattern(".title > .rt > strong");

        PickUpItem doubanScoreFloatNumber = new PickUpItem();
        doubanScoreFloatNumber.setMatchType(MatchType.Css);
        doubanScoreFloatNumber.setName("doubanScoreFloatNumber");
        doubanScoreFloatNumber.setPattern(".title > .rt > .fm");

        PageHelper page = new PageHelper();
        page.setDocument(Jsoup.parse(content));
        page.addPatternParts(nameAndTimeItem);
        page.addPatternParts(actorsItem);
        page.addPatternParts(urlItem);
        page.addPatternParts(doubanScore);
        page.addPatternParts(doubanScoreFloatNumber);
        Map<String, List<PickUpItem>> items = page.run();

        Movie movie = null;
        String cnName = null;
        String name = null;
        String year = null;
        String actors = null;
        String url = null;
        try {

            url = baseUrl + items.get("url").get(0).getTargetElement().attr("href");
            // <font color="#FF6600">非你勿扰<i>/非你勿扰</i>.2015</font>
            String nameStr = items.get("cnNameEnNameOrReleaseTime").get(0).getTargetElement().html();
            nameStr = nameStr.replaceAll("<font color=\"#FF6600\">", "").replaceAll("</font>", "").replaceAll("<i>", "").replaceAll("</i>", "")
                    .replace("/", ",");
            nameStr = nameStr.substring(0, (nameStr.lastIndexOf("."))) + "," + nameStr.substring((nameStr.lastIndexOf(".") + 1), nameStr.length());
            String[] split = nameStr.split(",");
            int size = split.length;
            for (int i = 0; i < split.length; i++) {
                if (i == 0) {
                    cnName = split[i];
                } else if (i == (size - 1)) {
                    year = split[i];
                } else {
                    if (StringUtils.isEmpty(name)) {
                        name = split[i];
                    } else {
                        name = name + "," + split[i];
                    }
                }
            }
            // 2015(中国大陆)<em>/</em>大左<em>/</em>姜潮<em>/</em>穆婷婷<em>/</em>肖旭<em>/</em>张磊<em>/</em>侍宣如<em>/</em>赵艺然
            String actorsStr = items.get("actors").get(0).getTargetElement().html();
            if (!StringUtil.isBlank(actorsStr)) {
                actors = actorsStr.substring(actorsStr.indexOf("<em>/</em>"), actorsStr.length()).replaceAll("<em>/</em>", ",");
            }

            String doubanfen = items.get("doubanScore").get(0).getTargetElement().html();
            String doubanfenFloat = items.get("doubanScoreFloatNumber").get(0).getTargetElement().html();

            movie = new Movie();
            movie.setSurl(url);
            movie.setSname(name);
            movie.setTitle(cnName);
            movie.setYear(year);
            movie.setActors(actors);
            movie.setScore((StringUtils.isEmpty(doubanfen) ? 0d : Double.valueOf(doubanfen))
                    + (StringUtils.isEmpty(doubanfenFloat) ? 0d : Double.valueOf(doubanfenFloat) / 10));
        } catch (Exception e) {

        }
        return movie;
    };

    public static void main(String[] args) {
        // String nameStr = "<font
        // color=\"#FF6600\">非你勿扰<i>/非你勿扰</i>.2015</font>";
        // nameStr = nameStr.substring(0, (nameStr.lastIndexOf(".")))
        // + nameStr.substring((nameStr.lastIndexOf(".") + 1),
        // nameStr.length());
        // System.out.println(nameStr);

        // Date date = DateUtils.parseDate("2015");
        // System.out.println(date);
    }

}
